<template>
  <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
    <div class="main-class" :style="{height:mainHeight+'px'}">
      <title>{{titleText}}</title>
      <!--  顶部选择设备  -->
      <van-dropdown-menu class="down-menu">
        <van-dropdown-item v-model="deviceId" :options="deviceList" @change="downMenuChange"/>
        <van-dropdown-item v-model="deviceId" disabled :options="deviceList"/>
      </van-dropdown-menu>
      <!--   顶部按钮   -->
      <van-button class="down-menu-btn" type="default" @click="openAddDevice">添加设备</van-button>
      <!--  弹窗    -->
      <van-dialog v-model="showDialog" title="添加设备"
                  :show-cancel-button="false"
                  :show-confirm-button="false"
                  :close-on-click-overlay="true">
        <bind-comp v-on:closeBindCompDialog="closeBindCompDialog"
                   scan-qr-margin-top="5%"
                   scan-qr-margin-bottom="5%"></bind-comp>
      </van-dialog>

      <!--      &lt;!&ndash;  天气面板  &ndash;&gt;-->
      <!--      <weather :region-text="regionText" :temp-number="tempNumber" :temp-details="tempDetails"-->
      <!--               v-if="tabType === 1"-->
      <!--               class="weather"></weather>-->

      <!--      &lt;!&ndash;   当前区域的空气质量   &ndash;&gt;-->
      <!--      <weather-mark></weather-mark>-->

      <!--  动画图表  -->
      <!--  只有实时数据的时候才会显示背景图   -->
      <!--      <van-image v-show="tabType === 1" class="dial-background-img" :src="background"/>-->
      <div v-if="tabType === 1" class="dial-canvas-div">
        <dial-v2 :key="dialKey" :on-line="onLine" :val="dialVal" :title-name="titleText" :limit="dialLimit"
                 :step="dialStep"
                 :dial-detail="dialDetail"
                 :dial-unit="dialUnit" class="dial-canvas"></dial-v2>
      </div>
      <charts class="charts" :xData="chartsXData" :data="chartsData" :text="chartsText" v-else></charts>

      <!--  中部面板图片   -->
      <div class="mid-bg-div">
        <img :src="MID_BJ_IMG"/>
      </div>

      <!--  打开底部按钮   -->
      <div class="open-footer-btn-div" :style="{top:openFooterBtnDivTop+'px'}">
        <img :src="ICON_DOWN_IMG"/>
      </div>

      <div class="fun-btn-group-parent" v-show="tabType === 1">
        <div class="fun-btn-group">
          <fun-grid-item type="C" state="1"></fun-grid-item>
          <fun-grid-item type="D" state="1"></fun-grid-item>
          <fun-grid-item type="E" state="1"></fun-grid-item>

          <fun-grid-item type="F" state="1"></fun-grid-item>
          <fun-grid-item type="G" state="1"></fun-grid-item>
          <fun-grid-item type="H" state="1"></fun-grid-item>
        </div>
      </div>

      <!--  tab按钮   -->
      <div class="tab-btn-group">
        <tab-button @click.native="setTab(1)" :isChecked="currDataBtnIsChecked" btn-text="实时数据"></tab-button>
        <tab-button @click.native="setTab(2)" :isChecked="weekDataBtnIsChecked" btn-text="周数据"></tab-button>
        <tab-button @click.native="setTab(3)" :isChecked="mouthDataBtnIsChecked" btn-text="月数据"></tab-button>
      </div>
    </div>
  </van-pull-refresh>
</template>
<script>
  import DialV2 from "@/components/DialV2";
  import Charts from "@/components/Charts";
  import TabButton from "@/components/TabButton";
  import FunButton from "@/components/FunButton";
  import Weather from "@/components/Weather";
  import {getUrlParam} from "@/util/GetUrlParam";
  import util from "@/util/util";
  import BindComp from "@/components/BindComp";
  import FunGridItem from "@/components/FunGridItem";
  import "@/util/inobounce.min";
  import WeatherMark from "@/components/WeatherMark";

  export default {
    data() {
      return {
        MID_BJ_IMG: require("@/images/mid_bg.png"), //中部背景
        ICON_DOWN_IMG: require("@/images/icon_down.png"), //打开底部按钮
        background: require("@/images/charts-background@2x.png"),
        isLoading: false,
        mainHeight: 0,
        openFooterBtnDivTop: 0,
        //功能按钮
        needMask: false,  //是否需要带口罩
        needOuterSport: false, //是否适合室外运动
        needOpenTheWindow: false, //是否适合开窗通风
        closeWindDevice: false, //关闭风机
        closePurifier: false, //关闭净化器
        startOuterFor: false, //开启外循环
        //tab按钮
        currDataBtnIsChecked: true,
        weekDataBtnIsChecked: false,
        mouthDataBtnIsChecked: false,
        //top按钮(顶部按钮)
        topBtnHCHOIsChecked: true, //甲醛
        topBtnPM25IsChecked: false, //PM2.5
        topBtnTVOCIsChecked: false, //TVOC
        topBtnCOIsChecked: false, //CO
        tabType: 1, //'1,实时数据；2，周数据,3，月数据',
        titleText: '',
        //天气来源
        weatherSource: '-数据来源于高德天气',
        //报表数据
        chartsText: '',
        chartsXData: [],//报表X轴数据
        chartsData: [], //报表数据
        //当前页面数据
        deviceId: '',
        meterType: 0,  //仪表类型
        meterTypeName: '', // 仪表类型名称
        //当前图表的数值
        dialKey: 0,
        dialVal: 0,
        //图表数据源
        sourceChartsData: {
          day: [],
          hours: []
        },
        deviceList: [],
        //图表单位
        dialUnit: '',
        //图表进度上限
        dialLimit: 100,
        //图表说明描述
        dialDetail: '合格',
        //图表进度步长
        dialStep: 1,
        //天气数据
        regionText: '---·---',
        tempNumber: '--',
        tempDetails: '--:--',
        //设备是否在线
        onLine: '0',
        //dialog展示
        showDialog: false,
      };
    },
    components: {
      // eslint-disable-next-line vue/no-unused-components
      WeatherMark,
      // eslint-disable-next-line vue/no-unused-components
      DialV2,
      // eslint-disable-next-line vue/no-unused-components
      Charts,
      TabButton,
      // eslint-disable-next-line vue/no-unused-components
      FunButton,
      // eslint-disable-next-line vue/no-unused-components
      Weather,
      BindComp,
      FunGridItem
    },
    mounted() {
      let that = this;
      that.init();
      // setInterval(() => {
      //   that.init();
      // }, 10000);
    },
    methods: {
      init() {
        let that = this
        //设置页面基准
        that.$setHTMLFontSise();
        addEventListener("resize", that.$setHTMLFontSise(), false);
        addEventListener("orientationchange", that.$setHTMLFontSise(), false); //移动端

        //整个页面的高度
        that.mainHeight = window.innerHeight + (window.innerHeight / 3);
        //打开底部按钮的上距离
        that.openFooterBtnDivTop = window.innerHeight - (3 * util.getFontSize());

        //加载设备信息
        let dId = getUrlParam('deviceId');
        that.deviceId = String(dId);
        //加载设备列表
        that.loadDevice();
        //加载图表数据
        that.loadChatsData();
        //加载天气信息
        that.loadWeather();
      },
      onRefresh() {
        let that = this;
        setTimeout(() => {
          that.init();
          that.isLoading = false;
        }, 1000);
      },
      //设置tab按钮状态
      _setTabBtnStatus(type) {
        let typeNumber = Number(type);
        if (typeNumber === 1) {
          this.currDataBtnIsChecked = true;
          this.weekDataBtnIsChecked = false;
          this.mouthDataBtnIsChecked = false;
        } else if (typeNumber === 2) {
          this.currDataBtnIsChecked = false;
          this.weekDataBtnIsChecked = true;
          this.mouthDataBtnIsChecked = false;
        } else if (typeNumber === 3) {
          this.currDataBtnIsChecked = false;
          this.weekDataBtnIsChecked = false;
          this.mouthDataBtnIsChecked = true;
        }
      },
      //修改tab
      setTab(type) {
        let that = this;
        let typeNumber = Number(type);
        that.tabType = typeNumber
        that._setTabBtnStatus(typeNumber)
        that.chartsXData = [];
        that.chartsData = [];
        if (typeNumber === 1) {
          that.chartsText = ''
        } else if (typeNumber === 2) {
          that.chartsText = '周数据'
          if (that.sourceChartsData.hours.length > 0) {
            // 设置周数据（当前月的历史数据，按每天平均AQI数据）
            let lastDate;
            for (let i = 0; i < that.sourceChartsData.hours.length; i++) {
              let dd = that.sourceChartsData.hours[i];
              let recordDate = dd.recordDate;
              let xPoint;
              //第一条
              if (!lastDate) {
                lastDate = recordDate;
                let recordDateArr = String(lastDate).split("-");
                let dateDay = recordDateArr[1] + '/' + recordDateArr[2];
                xPoint = dateDay + ' ' + dd.insertTime.hours + 'h';
              } else {
                //同一天
                if (lastDate === recordDate) {
                  lastDate = recordDate;
                  let recordDateArr = String(lastDate).split("-");
                  let dateDay = recordDateArr[1] + '/' + recordDateArr[2];
                  xPoint = '*' + dateDay + ' ' + dd.insertTime.hours + 'h';
                }
                //不同一天
                else {
                  lastDate = recordDate;
                  let recordDateArr = String(lastDate).split("-");
                  let dateDay = recordDateArr[1] + '/' + recordDateArr[2];
                  xPoint = dateDay + ' ' + dd.insertTime.hours + 'h';
                }
              }
              that.chartsXData.push(xPoint);
              that.chartsData.push(that.getChartsData(dd, Number(that.meterType)));
            }
          } else {
            that.chartsXData = ['01', '02', '03', '04', '05', '06', '07'];
            that.chartsData = [0, 0, 0, 0, 0, 0, 0];
          }
        } else if (typeNumber === 3) {
          that.chartsText = '月数据'
          if (that.sourceChartsData.day.length > 0) {
            // 设置月数据（当前月的历史数据，按每天平均AQI数据）
            for (let i = 0; i < that.sourceChartsData.day.length; i++) {
              let dd = that.sourceChartsData.day[i];
              let recordDate = dd.recordDate;
              let recordDateArr = String(recordDate).split("-");
              that.chartsXData.push(recordDateArr[1] + '/' + recordDateArr[2]);
              that.chartsData.push(that.getChartsData(dd, Number(that.meterType)));
            }
          } else {
            that.chartsXData = ['01', '02', '03', '04', '05', '06', '07'];
            that.chartsData = [0, 0, 0, 0, 0, 0, 0];
          }
        }
      },
      //通过设备类型获取对应数据
      getChartsData(data, meterType) {
        //甲醛
        if (meterType === 10041001) {
          return data.hchoAve;
        }
        //CO
        else if (meterType === 10041004) {
          return data.coAve;
        }
        //PM2.5
        else if (meterType === 10041003) {
          return data.pmAve;
        }
        //TVOC
        else if (meterType === 10041002) {
          return data.vocAve;
        } else {
          return 0;
        }
      },
      //关闭所有TOP按钮状态
      _closeTopBtnStatus() {
        this.topBtnHCHOIsChecked = false  //甲醛
        this.topBtnPM25IsChecked = false //PM2.5
        this.topBtnTVOCIsChecked = false //TVOC
        this.topBtnCOIsChecked = false //CO
      },
      loadDeviceInfo(meterType) {
        let that = this;
        let cook = that.$cookies.get(process.env.VUE_APP_COOKIE_USER_KEY);
        let id = cook.userInfo.id;
        let param = {
          userId: id,
          macAddress: that.deviceId
        };
        that.$http.restPost('/getConcentDataByMAC.do', param).then(response => {
          console.log(response.data)
          if (response.data) {
            if (response.data.datas) {
              //按照设备类型获取数据
              //该设备是否在线
              that.onLine = response.data.datas.onLine;
              //设置离线在线状态
              for (let i = 0; i < that.deviceList.length; i++) {
                let device = that.deviceList[i];
                if (device.value === that.deviceId) {
                  if (that.onLine === '0') {
                    device.text = device.text + '(离线)'
                  }
                }
              }
              console.log('设备是否在线：' + that.onLine);
              //甲醛
              if (meterType === 10041001) {
                that.dialVal = response.data.datas.data17;
                that.dialLimit = 2.5;
                that.dialStep = 0.01;
                that.dialUnit = 'mg/m³';
                if (that.dialVal > 0.08) {
                  that.dialDetail = '不合格'
                } else {
                  that.dialDetail = '合格'
                }
                //判断当前数值大于上限
                if (that.dialVal > that.dialLimit) {
                  that.dialLimit = that.dialVal;
                }
                that.dialStep = that.dialVal / 100
              }
              //CO
              else if (meterType === 10041004) {
                that.dialVal = response.data.datas.data31;
                if (that.dialVal > 5000) {
                  that.dialDetail = '不合格'
                } else {
                  if (that.dialVal > 300 && that.dialVal <= 450) {
                    that.dialDetail = '合格'
                  } else if (that.dialVal > 350 && that.dialVal <= 1000) {
                    that.dialDetail = '合格'
                  } else if (that.dialVal > 1000 && that.dialVal <= 2000) {
                    that.dialDetail = '不合格'
                  } else {
                    that.dialDetail = '合格'
                  }
                }
                that.dialStep = 1;
                that.dialLimit = 65535;
                that.dialUnit = 'PPM';
                //判断当前数值大于上限
                if (that.dialVal > that.dialLimit) {
                  that.dialLimit = that.dialVal;
                }
                that.dialStep = that.dialVal / 100
              }
              //PM2.5
              else if (meterType === 10041003) {
                that.dialVal = response.data.datas.data14;
                if (that.dialVal > 0 && that.dialVal <= 35) {
                  that.dialDetail = '优'
                } else if (that.dialVal > 35 && that.dialVal <= 75) {
                  that.dialDetail = '良'
                } else if (that.dialVal > 75 && that.dialVal <= 115) {
                  that.dialDetail = '轻度污染'
                } else if (that.dialVal > 115 && that.dialVal <= 150) {
                  that.dialDetail = '中度污染'
                } else if (that.dialVal > 150 && that.dialVal <= 250) {
                  that.dialDetail = '重度污染'
                } else {
                  that.dialDetail = '严重污染'
                }
                that.dialStep = 1;
                that.dialLimit = 1000;
                that.dialUnit = 'μg/m³';
                //判断当前数值大于上限
                if (that.dialVal > that.dialLimit) {
                  that.dialLimit = that.dialVal;
                }
                that.dialStep = that.dialVal / 100
              }
              //TVOC
              else if (meterType === 10041002) {
                that.dialVal = response.data.datas.data16;
                if (that.dialVal < 0.5) {
                  that.dialDetail = '合格'
                } else {
                  that.dialDetail = '不合格'
                }
                that.dialStep = 0.01;
                that.dialLimit = 1.23;
                that.dialUnit = 'mg/m³';
                //判断当前数值大于上限
                if (that.dialVal > that.dialLimit) {
                  that.dialLimit = that.dialVal;
                }
                that.dialStep = that.dialVal / 100
              } else {
                that.dialVal = 0;
                that.dialUnit = '-----------';
                alert('设备类型错误：meterType：' + that.meterType);
              }
              //更新图表
              that.updateDial();
            }
          }
        })
      },
      updateDial() {
        let that = this;
        that.dialKey = that.dialKey + 1;
      },
      //加载数据
      loadChatsData() {
        let that = this;
        let param = {
          macAddress: that.deviceId,
        };
        //获取月数据（当前月的历史数据，按每天平均AQI数据）
        that.$http.restPost('/getDeviceDatasDay.do', param).then(response => {
          if (response.data) {
            if (response.data.datas) {
              that.sourceChartsData.day = response.data.datas;
            }
          }
        });
        //获取周（为每两个小时一条）
        that.$http.restPost('/getDeviceDatasHour.do', param).then(response => {
          if (response.data) {
            if (response.data.datas) {
              that.sourceChartsData.hours = response.data.datas;
            }
          }
        });
      },
      loadDevice() {
        let that = this;
        that.deviceList = [];
        let cook = that.$cookies.get(process.env.VUE_APP_COOKIE_USER_KEY);
        let id = cook.userInfo.id;
        let param = {
          userId: id,
          userType: 2
        };
        that.$http.restPost('/findUserDeviceList.do', param).then(res => {
          let data = res.data;
          let appUserDevice = data.AppUserDevice;
          if (appUserDevice) {
            if (appUserDevice.length > 0) {
              for (let i = 0; i < appUserDevice.length; i++) {
                let deviceCode = appUserDevice[i].deviceCode;
                let deviceName = appUserDevice[i].deviceName;
                let meterType = appUserDevice[i].meterType;
                let meterTypeName = appUserDevice[i].meterTypeName;
                //设置title(当前设备的设备ID)
                if (that.deviceId === deviceCode) {
                  that.meterType = meterType;
                  that.meterTypeName = meterTypeName;
                  that.titleText = that.meterTypeName;
                  //加载当前页面数据
                  that.loadDeviceInfo(Number(that.meterType))
                }
                that.deviceList.push({value: deviceCode, text: deviceName});
              }
            }
          }
        })
      },
      //下拉菜单改变数据
      downMenuChange(value) {
        location.href = 'main.html?deviceId=' + value
      },
      //加载天气数据
      loadWeather() {
        let that = this;
        //获取地理位置
        that.$wechat.ready(() => {
          that.$wechat.getLocation({
            type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
            success: function (res) {
              let latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90  lat纬度
              let longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。 lng经
              let param = {
                longitude: longitude,
                latitude: latitude,
              };
              that.$http.restPost('/getWeather.do', param).then((res) => {
                let data = res.data;
                if (data.result === 1) {
                  if (data.data.lives && data.data.lives.length > 0) {
                    let live = data.data.lives[0];
                    //温度摄氏度
                    let temperature = live.temperature;
                    //省份
                    let province = live.province;
                    //区
                    let city = live.city;
                    //天气情况
                    let weather = live.weather;
                    //天气数据
                    that.regionText = province + '·' + city;
                    that.tempNumber = '' + temperature;
                    that.tempDetails = '天气:' + weather;
                  }
                } else {
                  alert('天气获取失败')
                }
              })
            }
          });
        });
      },
      //添加设备
      openAddDevice() {
        let that = this;
        that.showDialog = !that.showDialog;
      },
      //BindComp子组件回调关闭弹窗
      closeBindCompDialog() {
        let that = this;
        //关闭添加设备弹窗
        that.openAddDevice();
      },
    },

  }
</script>
<style lang="css" scoped>
  .main-class {
    overflow: auto;
    width: 100%;
    background-image: url("../../images/charts-background@2x.png");
    background-size: 100% 100%;
  }

  /* 天气面板 */
  .weather {
    top: 5.3rem;
    left: 3rem;
    position: fixed;
  }

  /* 数据来源 */
  .weather-source {
    top: 5.3rem;
    right: 3rem;
    font-size: 1.1rem;
    position: fixed;
    color: white;
  }

  /* tab按钮 */
  .tab-btn-group > :nth-child(2) {
    margin: 0 1.2rem 0 1.2rem;
  }

  .tab-btn-group {
    width: 100%;
    text-align: center;
    position: relative;
    bottom: -26.45rem;
  }

  .fun-btn-group-parent {
    width: 100%;
    text-align: center;
    position: relative;
    bottom: -24rem;
  }

  .fun-btn-group {
    display: inline-grid;
    grid-row-gap: 1rem;
    grid-column-gap: 1rem;
    grid-template-columns: 4.5rem 4.5rem 4.5rem;
    grid-template-rows: 5rem 5rem;
    justify-items: stretch;
    align-items: stretch;
    position: relative;
  }

  /* 表盘DIV */
  .dial-canvas-div {
    width: 100%;
    position: relative;
    top: 4rem;
    text-align: center;
  }

  /* 表盘 */
  .dial-canvas {
    display: inline-block;
  }

  /* 报表 */
  .charts {
    position: fixed;
    top: 15%;
  }

  .fun-group-text p {
    margin: 0;
    padding: 0;
    width: 100%;
    text-align: center;
    font-weight: Bold;
    font-size: 1.2rem;
  }

  /*  表盘背景图*/
  .dial-background-img {
    width: 100%;
    height: 100%;
    position: relative;
    z-index: -9999999;
  }

  .down-menu {
    height: 3.3rem;
    width: 100%;
    position: fixed;
    z-index: 9999999;
  }

  .down-menu-btn {
    width: 50%;
    height: 3.1rem;
    display: inline-block;
    position: fixed;
    z-index: 99999999;
    top: 0.10462rem;
    right: 0;
    border: 0;
  }

  .fun-btn-group-1 > *, .fun-btn-group-2 > * {
    margin: 0 1.1rem 0 1.1rem;
  }

  /* 中部面板DIV */
  .mid-bg-div {
    width: 100%;
    position: relative;
    top: 2rem;
    text-align: center;
  }

  .mid-bg-div > img {
    width: 23rem;
    height: 6rem;
  }

  .open-footer-btn-div {
    width: 100%;
    position: absolute;
    text-align: center;
  }
</style>
